package 二叉树.遍历;

import 二叉树.TreeNode;

import java.util.Stack;

public class DLR {

    public static void traversal(TreeNode root) {
        if (root != null) {
            System.out.print(root.val + " ");
            traversal(root.left);
            traversal(root.right);
        }
    }

    // 非递归实现
    public static void preorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack();
        while (root != null || !stack.isEmpty()) {
            // 一直遍历到最左叶子节点
            while (root != null) {
                System.out.print(root.val + " ");
                stack.push(root);
                root = root.left;
            }

            if (!stack.isEmpty()) {
                root = stack.pop();
                root = root.right;
            }
        }
    }
}
